<template>
    <div class="course-list flex flex-col sm:flex-row dark:bg-regal-dark w-full">
        <div :class="'w-full ml-0 sm:ml-2 mt-2 sm:mt-0' ">
            <Search :search="search" :reset="reset">
                <template v-slot:body>
                    <el-form-item label="用户名">
                        <el-input v-model="query.user_name" placeholder="请输入" style="width: 180px"></el-input>
                    </el-form-item>
                    <el-form-item label="老师名">
                        <el-select
                            v-model="query.teacher_id"
                            placeholder="请选择"
                            style="width: 160px"
                        >
                            <el-option
                                v-for="item in lessonConfig.teacherList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                </template>
            </Search>
            <div class="table-default">
                <div class="pt-5 pl-2 flex align-middle" v-if="isSuperManage">
                    <el-button type="primary" @click="addCustomer"><Icon name="plus" className="w-4 h-4 mr-1" /> 添加客户</el-button>
                </div>
                <el-table
                    :data="tableData"
                    style="width: 100%;height: calc(100% - 100px);" border class="mt-3"
                    row-key="id"
                    default-expand-all
                >
                    <el-table-column
                        v-for="item in headerConfig"
                        :key="item.prop"
                        :prop="item.prop"
                        :label="item.label"
                    >
                        <template #default="{ row }">
                            <template v-if="item.prop === 'last_lessons'">
                                <span :class="{'red': row[item.prop] < 50}"> {{row[item.prop] || 0 }}</span>
                            </template>
                            <template v-else>
                                <span>{{ row[item.prop] }}</span>
                            </template>

                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="220">
                        <template #default="{ row }" >
                            <template v-if="row.is_customer">
                                <el-button type="text" size="small" @click="lessonTimeRecord(row)">课时记录</el-button>
                                <el-button type="text" size="small" v-if="isSuperManage" @click="edit(row)">编辑</el-button>
                                <el-button type="text" size="small" v-if="isSuperManage" @click="deleteCustomer(row)">删除</el-button>
                            </template>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination class="mt-3" background layout="prev, pager, next" @current-change="changePage" @size-change="changeLimit"  :current-page="Pages.current_page" :page-sizes="Pages.per_page" :total="Pages.total" />
            </div>

            <el-dialog v-model="visible" :title="`${form.id ? '编辑' : '添加'}客户`" destroy-on-close>
                <div class="edit-dialog">
                    <el-form label-width="120px" :model="form" :rules="rules" ref="formRef">
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="form.username" placeholder="请输入"></el-input>
                        </el-form-item>
                        <el-form-item label="用户手机号" prop="phone">
                            <el-input v-model="form.phone" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="visible = false">取消</el-button>
                        <el-button type="primary" @click="saveConfirm">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import Http from '/admin/support/http'
import { Code } from '/admin/enum/app'
import Message from '/admin/support/message'
import { useUserStore } from '/admin/stores/modules/user'
import { ElMessageBox } from 'element-plus'
import router from '/admin/router'
const lessonConfig = ref({})
const userStore = useUserStore()


const isSuperManage = ref(userStore.getId === 1)

const query = ref({
    user_name: '',
    teacher_id: '',
})

const Pages = {
    current_page: 1,
    per_page: 10,
    total: 0
}

// 日历table 的头部配置
const headerConfig = [
    {
        prop: 'customer_number',
        label: '用户编号',
    },
    {
        prop: 'customer_name',
        label: '用户名',
    },
    {
        prop: 'last_lessons',
        label: '剩余课时（分钟）',
    },
    {
        prop: 'check_lessons',
        label: '审核中课时（分钟）',
    },
    {
        prop: 'complete_lessons',
        label: '已上课时（分钟）',
    },
]
const tableData = ref([
    {
        id: 1,
        customer_number: '1',
        customer_name: '张三',
        last_lessons: 100,
        check_lessons: 100,
        complete_lessons: 100,
        children: [
            {
                customer_number: '1',
                customer_name: '张三',
                last_lessons: 100,
                check_lessons: 100,
                complete_lessons: 100,
            },
            {
                customer_number: '1',
                customer_name: '张三',
                last_lessons: 100,
                check_lessons: 100,
                complete_lessons: 100,
            },
        ],
    },
    {
        id: 2,
        customer_number: '2',
        customer_name: '李四',
        last_lessons: 100,
        check_lessons: 100,
        complete_lessons: 100,
        children: [
            {
                customer_name: '张三',
                last_lessons: 100,
                check_lessons: 100,
                complete_lessons: 100,
            },
            {
                customer_name: '张三',
                last_lessons: 100,
                check_lessons: 100,
                complete_lessons: 100,
            },
        ],
    },
])



const changePage = (val: number) => {
    Pages.current_page = val
    search()
}

const changeLimit = (val: number) => {
    Pages.per_page = val
    search()
}

const reset = () => {
    query.value = {
        user_name: '',
        teacher_id: '',
    }
    search()
}

const search = async () => {
    const params = {
        user_name: query.value.user_name,
        teacher_id: query.value.teacher_id,
        page: Pages.current_page,
        limit: Pages.per_page
    }
    const { data } = await Http.get('/customer/list', params)
    if (data.code === Code.SUCCESS) {
        tableData.value = data.data
        Pages.total = data.total
    } else {
        Message.error(data.message)
    }
}


const getLessonConfig = async () => {
    const { data } = await Http.get('/lessonHour/lessonConfig')
    if (data.code === Code.SUCCESS) {
        lessonConfig.value = data.data
    } else {
        Message.error(data.message)
    }
}


getLessonConfig()
search()
const lessonTimeRecord = (row: any) => {
    router.push({ path: '/lesson-hour/index', query: { customer_id: row.id } })
}

const edit = (row: any) => {
    console.log(row, 'row')
    form.value.id = row.id
    form.value.username = row.customer_name
    form.value.phone = row.phone
    visible.value = true
}
const deleteConfirm = (row: any) => {
    console.log(row, 'row')
}

const visible = ref(false)
const form = ref({
    id: '',
    username: '',
    phone: '',
})
const formRef = ref(null)
const rules = ref({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' , max: 10}],
    phone: [
        { required: true, message: '请输入用户手机号', trigger: 'blur' },
        { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],
})

const addCustomer = () => {
    form.value = {
        id: '',
        username: '',
        phone: '',
    }
    visible.value = true
}

const saveConfirm = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            const params = {
                username: form.value.username,
                phone: form.value.phone,
            }
            if (form.value.id) {
                params.id = form.value.id
            }
            const { data } = await Http.post(params.id ? '/customer/update' :'/customer/add', params)
            if (data.code === Code.SUCCESS) {
                visible.value = false
                search()
                Message.success('保存成功')
            } else {
                Message.error(data.message)
            }
        } else {
            console.log('error submit!!')
            return false
        }
    })
}

//删除用户
const deleteCustomer = async (row: object) => {
    ElMessageBox.confirm(
        '确定删除该用户?',
        '警告',
        {
            type: 'warning',
        }
    )
        .then(async () => {
            const { data } = await Http.post('/customer/delete', { id: row.id })
            if (data.code === Code.SUCCESS) {
                search()
                Message.success('删除成功')
            } else {
                Message.error(data.message)
            }
        })
        .catch(() => {

        })

}
</script>

<style scoped lang="scss">
.red {
    color: red;
}
.course-list {
    height: calc(100vh - 120px);
}
.table-default {
    height: calc(100% - 120px);
}
.course-table {
    background: #fff;
    .table {
        width: 100%;
        border: 1px solid #ebeef5;
        border-radius: 8px;
        .course-header {
            height: 60px;
            td {
                text-align: center;
                border-right: 1px solid #ebeef5;
                border-bottom: 1px solid #e1e4e8;
            }
        }
        .course-tr {
            border-bottom: 1px solid #e1e4e8;

            .time {
                width: 100px;
                text-align: center;
                border-right: 1px solid #ebeef5;
            }
            .course-item {
                border-right: 1px solid #ebeef5;
                width: calc(100% / 7.6);
                height: 110px;
                padding: 4px;
                .active {
                    height: 100%;
                    color: #7C93C3;
                    background: #DFF5FF;
                    border-radius: 4px;
                    padding: 10px;
                }
            }
        }
    }
}
.edit-dialog {
    padding: 36px;
}
</style>
